package com.liu.tools.qiuniu;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.liu.tools.StrUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

/**
 * @DateTime 2015年1月12日 下午2:36:06
 * @Company 华视传媒
 * @Author 刘兴密
 * @QQ 63972012
 * @Desc 七牛云存储工具类
 */
public class QiniuHelper {

	private static Logger logger = LoggerFactory.getLogger(QiniuHelper.class);
    
	private static QiniuHelper instance;
	
	private static QiniuConfig config;
	
	private static Auth auth;
	
	private static BucketManager bucketManager;
	
	private QiniuHelper(){
		
	}
	
	public static QiniuHelper getInstance(){
		
		if(instance == null){
		   	synchronized (QiniuHelper.class) {
		   		if(instance == null){
			   		config = new QiniuConfig();
			   		auth = Auth.create(config.getAccessKey(), config.getSecretKey());
			   		bucketManager = new BucketManager(auth);
					instance = new QiniuHelper();
		   		}
			}			
		}
		
		return instance;
	}
	
    public synchronized static QiniuHelper getInstance(String accessKey, String secretKey, String bucketName,
			String uploadUrl, String domain, String picViewParam, int bucketType){
	
		if(instance == null){
		   	synchronized (QiniuHelper.class) {
		   		if(instance == null){
		   			config = new QiniuConfig(accessKey, secretKey, bucketName, uploadUrl, domain, picViewParam, bucketType);
		   			auth = Auth.create(config.getAccessKey(), config.getSecretKey());
		   			bucketManager = new BucketManager(auth);
					instance = new QiniuHelper();
		   		}
			}			
		}
		
		return instance;
	}
	
	/**
	 * @DateTime 2015年1月12日 下午2:39:25
	 * @Author 刘兴密
	 * @QQ 63972012
	 * @Desc 上传信息
	 * @return
	 * @throws Exception
	 * Map<String,String>
	 */
	public Map<String, String> getUploadInfo() throws Exception{
		
		if(config == null){
			logger.info("QiniuHelper:getUploadInfo", "", "config is null");
			return null;
		}
		
		logger.info("QiniuHelper:getUploadInfo", "", "获取七牛文件上传信息");
       
        String uptoken = "";  
        uptoken = getToken("");        
		Map<String, String> map = new HashMap<String, String>();
		map.put("token", uptoken);
		map.put("uploadUrl", config.getUploadUrl());
		logger.info("QiniuHelper:getUploadInfo", "", "七牛文件上传信息：" + JSON.toJSONString(map));
		return map;
	}
	
	/**
	 * @DateTime 2015年1月12日 下午3:01:47
	 * @Author 刘兴密
	 * @QQ 63972012
	 * @Desc 文件下载url生成
	 * @param fileName
	 * @return
	 * @throws Exception
	 * Map<String,String>
	 */
	public String getDownloadInfo(String domain, String fileName) throws Exception{
		
		if(config == null){
			logger.info("QiniuHelper:getUploadInfo", "", "config is null");
			return null;
		}
		
		logger.info("QiniuHelper:getDownloadInfo", "", "获取七牛文件下载url, fileName=" + fileName);
		
		if(StrUtil.isNull(domain)){
	        	domain = config.getDomain();
	    }
		String baseUrl = StrUtil.makeUrl(domain, fileName);   
        if(config.getBucketType() == 0){
        	logger.info("QiniuHelper:getDownloadInfo", "", "该空间为公共空间，七牛文件下载url, downloadUrl=" + baseUrl);
        	return baseUrl;
        }
		
        String downloadUrl = auth.privateDownloadUrl(baseUrl, 3600*24*365*10);
        
        logger.info("QiniuHelper:getDownloadInfo", "", "七牛文件下载url, downloadUrl=" + downloadUrl);
        return downloadUrl;
	}
	
	
	/**
	 * @DateTime 2015年1月12日 下午3:01:47
	 * @Author 刘兴密
	 * @QQ 63972012
	 * @Desc 文件下载url生成
	 * @param fileName
	 * @return
	 * @throws Exception
	 * Map<String,String>
	 */
	public String getThumDownloadInfo(String domain, String fileName) throws Exception{
		
		if(config == null){
			logger.info("QiniuHelper:getUploadInfo", "", "config is null");
			return null;
		}
		
		logger.info("QiniuHelper:getDownloadInfo", "", "获取七牛文件下载url, fileName=" + fileName);
		
		if(StrUtil.isNull(domain)){
	        	domain = config.getDomain();
	    }
		
		String thumUrl = StrUtil.makeUrl(domain, fileName) + "?" + config.getPicViewParam();
	        
        if(config.getBucketType() == 0){

        	logger.info("QiniuHelper:getDownloadInfo", "", "该空间为公共空间，七牛文件下载url, downloadUrl=" + thumUrl);
        	return thumUrl;
        }
        
        String baseUrl = StrUtil.makeUrl(thumUrl, fileName);

        String downloadUrl = auth.privateDownloadUrl(baseUrl, 3600*24*365*10);
        logger.info("QiniuHelper:getDownloadInfo", "", "七牛文件下载url, downloadUrl=" + downloadUrl);
        return downloadUrl;
	}
	
	
	
	/**
	 * @DateTime 2015年1月12日 下午3:46:58
	 * @Author 刘兴密
	 * @QQ 63972012
	 * @Desc 删除文件
	 * @param fileName
	 * void
	 */
	public int deleteFile(String fileName){
		
		if(config == null){
			logger.info("QiniuHelper:getUploadInfo", "", "config is null");
			return -1;
		}
		
		try {
			bucketManager.delete(config.getBucketName(), fileName);
		} catch (QiniuException e) {
			logger.error("QiniuHelper:batchDeleteFile", "", "删除七牛存储文件异常", e);
			return -1;
		}
		
        logger.info("QiniuHelper:batchDeleteFile", "", "删除七牛存储文件结果");
        return 200;

	}
	

	/**
	 * @DateTime 2015年7月22日 上午11:41:28
	 * @Author 刘兴密
	 * @QQ 63972012
	 * @Desc 上传文件
	 * @param file
	 * @param fileName
	 * @throws Exception
	 * void
	 */
	public String uploadFile(File file, String fileName) throws Exception{
		
		if(config == null){
			logger.info("QiniuHelper:getUploadInfo", "", "config is null");
			return "";
		}
		
		UploadManager uploadManager =  new UploadManager();
		String token = getToken(fileName);

		Response response = uploadManager.put(file, fileName, token);
		if(response.isOK()){
			
			logger.debug("QiniuHelper:uploadFile", "", "上传文件成功， fileName:" + fileName);
			String downloadUrl = getDownloadInfo(config.getDomain(), fileName);
			logger.debug("QiniuHelper:uploadFile", "", "生成下载地址成功， downloadUrl:" + downloadUrl);
			return downloadUrl;
	
		} else {
			logger.info("QiniuHelper:uploadFile", "", "上传文件失败， 失败信息信息：" + response.toString() + "  fileName:" + fileName);
		}
		
		return "";
	}

	public String uploadFile(byte[] data, String fileName) throws Exception{
		
		if(config == null){
			logger.info("QiniuHelper:getUploadInfo", "", "config is null");
			return "";
		}
		
		UploadManager uploadManager =  new UploadManager();
		String token = getToken(fileName);

		Response response = uploadManager.put(data, fileName, token);
		if(response.isOK()){
			
			logger.debug("QiniuHelper:uploadFile", "", "上传文件成功， fileName:" + fileName);
			String downloadUrl = getDownloadInfo(config.getDomain(), fileName);
			logger.debug("QiniuHelper:uploadFile", "", "生成下载地址成功， downloadUrl:" + downloadUrl);
			return downloadUrl;
	
		} else {
			logger.info("QiniuHelper:uploadFile", "", "上传文件失败， 失败信息信息：" + response.toString() + "  fileName:" + fileName);
		}
		
		return "";
	}
	
	/**
	 * @DateTime 2015年8月31日 下午3:54:20
	 * @Author 刘兴密
	 * @QQ 63972012
	 * @Desc 生成上传 token
	 * @param fileName
	 * @return
	 * String
	 */
	public String getToken(String fileName){
		
		String token = "";
		if(StrUtil.isNull(fileName)){
			token = auth.uploadToken(config.getBucketName());
		} else {
			token = auth.uploadToken(config.getBucketName(), fileName);
		}
		
		return token;
	}

}
